package com.itheima.app.controller;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserManager userManager;

    //保存
    @PostMapping("/user/save")
    public ResponseEntity saveUser(@RequestBody User user) {
        Long saveId = userManager.save(user);
        return ResponseEntity.ok(saveId);

    }
    //根据手机号查询用户
    @GetMapping("/user/findByPhone")
    public ResponseEntity findByPhone(String phone) {
        System.out.println(phone);
        User user = userManager.findByPhone(phone);
        return ResponseEntity.ok(user);

    }
    //发送短息验证码
    @PostMapping("/user/login")
    public ResponseEntity login(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        userManager.sendSmsLoginOrRegister(phone);
        return ResponseEntity.ok(null);
    }
    //02 登录---验证码校验
    @PostMapping("/user/loginVerification")//登录
    public ResponseEntity loginVerification(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");

        return userManager.loginOrRegister(phone, verificationCode);
    }
    //保存用户的基本数据-03 首次登录---完善资料
    @PostMapping("/user/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo,
                                       @RequestHeader("Authorization") String token) {
        userManager.saveUserInfo(userInfo, token);
        return ResponseEntity.ok(null);
    }
//添加 更换头像
    @PostMapping({"/user/loginReginfo/head","/users/header"})
    public ResponseEntity loginReginfoHead(MultipartFile headPhoto,
                                           @RequestHeader("Authorization") String token) throws IOException {

        userManager.saveUserHead(headPhoto, token);
        return ResponseEntity.ok(null);
    }
    //用户资料 - 读取
    @GetMapping("/users")
    public ResponseEntity findUserInfo(String userId,
                                       @RequestHeader("Authorization") String token) {
        return userManager.findUserInfo(userId, token);
    }
    //用户资料 -  修改
    @PutMapping("/users")
    public void updateUserInfo(@RequestBody UserInfo userInfo
            , @RequestHeader("Authorization") String token) {
        userManager.updateUserInfo(userInfo,token);
    }


}
